import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/register")
public class  RegisterServlet extends HttpServlet {

    // 处理GET请求（显示注册页面）
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 清除旧的验证码
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute("code");
        }
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }

    // 处理POST请求（提交注册）
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 1. 获取参数并验证基础格式
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String inputCode = request.getParameter("code");

        // 2. 参数基础校验
        if (username == null || username.trim().isEmpty()) {
            forwardError(request, response, "用户名不能为空");
            return;
        }
        if (password == null || password.trim().isEmpty()) {
            forwardError(request, response, "密码不能为空");
            return;
        }
        if (inputCode == null || inputCode.trim().isEmpty()) {
            forwardError(request, response, "验证码不能为空");
            return;
        }

        // 3. 验证码校验（区分大小写）
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("code");

        // 重要：验证后立即清除验证码（防止重复使用）
        session.removeAttribute("code");

        if (sessionCode == null || !sessionCode.equals(inputCode)) {
            forwardError(request, response, "验证码错误或已过期");
            return;
        }

        // 4. 执行注册逻辑
        try {
            UserRepository userService = new UserRepository();

            // 检查用户名是否已存在
            if (userService.usernameExists(username)) {
                forwardError(request, response, "用户名已被注册");
                return;
            }

            // 创建用户（生产环境需加密密码）
            User newUser = new User(username, password);
            userService.register(newUser);

            // 注册成功重定向到登录页
            response.sendRedirect(request.getContextPath() + "/login.jsp");

        } catch (Exception e) {
            // 记录系统日志
            getServletContext().log("用户注册失败", e);
            forwardError(request, response, "系统繁忙，请稍后重试");
        }
    }

    // 统一错误处理方法
    private void forwardError(HttpServletRequest request,
                              HttpServletResponse response,
                              String errorMessage)
            throws ServletException, IOException {
        request.setAttribute("registerError", errorMessage);
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }
}